﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace NeonMika.Webserver.ClientLibrary
{
    abstract public class Command
    {
        // Fields
        public string Url { get; set; }
        public string IP { get; set; }
        public string Name { get; set; }
        public string[] NeededParameters { get; private set; }
        public string LastResponse { get; private set; }

        protected Dictionary<string, object> parameter;

        // Constructors
        public Command(string url, string name, string[] neededParameters)
            : this("", url, name, neededParameters)
        {
        }

        public Command(string ip, string url, string name, string[] neededParameters)
        {
            this.IP = ip;
            this.Url = url;
            this.Name = name;
            this.parameter = new Dictionary<string, object>();
            this.NeededParameters = neededParameters;
        }

        public void AddParameter(string parameter, object value)
        {
            this.parameter.Add(parameter, value);
        }

        public void ClearParameter()
        {
            this.parameter = new Dictionary<string, object>();
        }

        public void Execute(string ip) {
            this.IP = ip;
            Stream responseStream = GetResponseStream();
            StreamReader sr = new StreamReader(responseStream);
            LastResponse = sr.ReadToEnd();
        }

        protected Stream GetResponseStream()
        {
            string completeURL = Path.Combine("http:\\", IP, Url);
            if (parameter.Count > 0)
                completeURL += "?";

            for (int i = 0; i < parameter.Count(); i++)
            {
                completeURL += parameter.ElementAt(i).Key + "=" + parameter.ElementAt(i).Value;
                if (i + 1 < parameter.Count)
                    completeURL += "&";
            }

            completeURL = "http://"+completeURL.Substring(6).Replace('\\', '/');

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(completeURL);
            return request.GetResponse().GetResponseStream();
        }
    }
}
